<!-- src/views/student/ApplicationHistory.vue -->
<template>
  <div class="application-history">
    <div class="header">
      <el-page-header @back="goBack">
        <template #content>
          <span class="title">实习申请记录</span>
        </template>
      </el-page-header>
      <div class="actions">
        <el-button type="primary" @click="goToPositions">申请新岗位</el-button>
      </div>
    </div>

    <!-- 申请列表 -->
    <el-table
        :data="applications"
        v-loading="loading"      style="width: 100%"
        class="application-table"
    >
      <el-table-column prop="companyName" label="企业名称" min-width="150" />
      <el-table-column prop="positionTitle" label="岗位名称" min-width="150" />
      <el-table-column prop="appliedAt" label="申请时间" min-width="180">
        <template #default="scope">
          {{ formatDate(scope.row.appliedAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="申请状态" min-width="120">
        <template #default="scope">
          <el-tag :type="getApplicationStatusType(scope.row.status)">
            {{ getApplicationStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button size="small" @click="viewApplicationDetail(scope.row)">查看详情</el-button>
          <el-button
              size="small"
              type="danger"
              @click="cancelApplication(scope.row)"
              :disabled="!canCancelApplication(scope.row.status)"
              v-if="canCancelApplication(scope.row.status)"
          >
            取消申请
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"      style="margin-top: 20px; justify-content: center;"
    />

    <!-- 申请详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="申请详情"
        width="60%"
    >
      <div v-if="selectedApplication" class="application-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="企业名称">{{ selectedApplication.companyName }}</el-descriptions-item>
          <el-descriptions-item label="岗位名称">{{ selectedApplication.positionTitle }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDate(selectedApplication.appliedAt) }}</el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <el-tag :type="getApplicationStatusType(selectedApplication.status)">
              {{ getApplicationStatusLabel(selectedApplication.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理时间" v-if="selectedApplication.processedAt">
            {{ formatDate(selectedApplication.processedAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="拒绝原因" v-if="selectedApplication.rejectReason">
            {{ selectedApplication.rejectReason }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="cover-letter-section" v-if="selectedApplication.coverLetter">
          <h3>求职信</h3>
          <p>{{ selectedApplication.coverLetter }}</p>
        </div>

        <div class="resume-section" v-if="selectedApplication.resumeUrl">
          <h3>简历</h3>
          <el-link :href="selectedApplication.resumeUrl" target="_blank">查看简历</el-link>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 取消申请确认对话框 -->
    <el-dialog
        v-model="cancelDialogVisible"
        title="确认取消申请"
        width="30%"
    >
      <span>确定要取消对 {{ cancelApplicationData?.positionTitle }} 岗位的申请吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancelApplication" :loading="cancelLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useStudentStore } from '../../store/student'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const studentStore = useStudentStore()
const router = useRouter()

const applications = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const cancelDialogVisible = ref(false)
const cancelLoading = ref(false)
const selectedApplication = ref({})
const cancelApplicationData = ref({})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取申请记录
const fetchApplications = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage - 1,
      size: pagination.pageSize
    }
    const response = await studentStore.fetchApplications(params)
    applications.value = response.content || response
    pagination.total = response.totalElements || 0
  } catch (error) {
    ElMessage.error('获取申请记录失败')
  } finally {
    loading.value = false
  }
}

// 查看申请详情
const viewApplicationDetail = async (application) => {
  try {
    const response = await studentStore.fetchApplicationDetail(application.id)
    selectedApplication.value = response
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取申请详情失败')
  }
}

// 跳转到岗位列表
const goToPositions = () => {
  router.push('/student/positions')
}

// 取消申请
const cancelApplication = (application) => {
  cancelApplicationData.value = application
  cancelDialogVisible.value = true
}

// 确认取消申请
const confirmCancelApplication = async () => {
  cancelLoading.value = true
  try {
    await studentStore.cancelApplication(cancelApplicationData.value.id)
    ElMessage.success('申请已取消')
    cancelDialogVisible.value = false
    await fetchApplications()
  } catch (error) {
    ElMessage.error('取消申请失败: ' + (error.response?.data?.message || error.message))
  } finally {
    cancelLoading.value = false
  }
}

// 检查是否可以取消申请
const canCancelApplication = (status) => {
  // 只有状态为0(待处理)的申请可以取消
  return status === 0
}

// 获取申请状态标签类型
const getApplicationStatusType = (status) => {
  switch (status) {
    case 0: return 'warning'  // 待处理
    case 1: return 'success'  // 已通过
    case 2: return 'danger'   // 已拒绝
    case 3: return 'info'     // 已取消
    default: return ''
  }
}

// 获取申请状态标签文本
const getApplicationStatusLabel = (status) => {
  switch (status) {
    case 0: return '待处理'
    case 1: return '已通过'
    case 2: return '已拒绝'
    case 3: return '已取消'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
}

// 分页事件处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchApplications()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchApplications()
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

onMounted(() => {
  fetchApplications()
})
</script>

<style scoped>.application-history {
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

/* 加宽表格列以适配信息显示 */
.application-table {
  margin-bottom: 20px;
}

:deep(.el-table__cell) {
  padding: 12px 15px;
}

:deep(.el-table .el-table__row) {
  height: 50px;
}

.cover-letter-section,
.resume-section {
  margin-top: 25px;
}

.cover-letter-section h3,
.resume-section h3 {
  margin-bottom: 12px;
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>